package com.est.android.wordtime;

import java.util.Calendar;

import com.est.android.wordtime.R;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class WordTimeWidgetConfig extends Activity {
	Button configOkButton;
	int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setResult(RESULT_CANCELED);
		
		setContentView(R.layout.config);
		
		configOkButton = (Button)findViewById(R.id.btnConfOk);
		configOkButton.setOnClickListener(btnConfOkOnClickListener);
		
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		
		if(extras != null) {
			mAppWidgetId = extras.getInt(
					AppWidgetManager.EXTRA_APPWIDGET_ID,
					AppWidgetManager.INVALID_APPWIDGET_ID);
		}
		
		if(mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID){
			finish();
		}
	}
	
	private Button.OnClickListener btnConfOkOnClickListener = new Button.OnClickListener() {

		public void onClick(View v) {
			final Context context = WordTimeWidgetConfig.this;
			
			AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
			
			WordTimeWidget.updateWordTimeWidget(context, appWidgetManager, mAppWidgetId);
			
			// This puts the clock on a schedule to keep it updated with the current time
			Intent intent = new Intent(WordTimeWidget.WORDTIME_UPDATE_INTENT);
			PendingIntent pendingIntent = PendingIntent.getBroadcast(WordTimeWidgetConfig.this, RESULT_OK, intent, 0);
			AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(System.currentTimeMillis());
			calendar.add(Calendar.SECOND, 10);
			alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), WordTimeWidget.CLOCK_UPDATE_RATE, pendingIntent);
			
			WordTimeWidget.SaveAlarmManager(alarmManager, pendingIntent);
			
			Intent resultValue = new Intent();
			resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
			setResult(RESULT_OK, resultValue);
			finish();
		}
	};
}
